﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ikvm.extensions;
using java.lang;
using String = System.String;
using StringBuilder = System.Text.StringBuilder;

namespace Game.utils
{
    public class SqlBatch
{
	/**
	 * Field _header.
	 */
	private String _header;
	/**
	 * Field _tail.
	 */
	private String _tail;
	/**
	 * Field _sb.
	 */
	private StringBuilder _sb;
	/**
	 * Field _result.
	 */
	private StringBuilder _result;
	/**
	 * Field _limit.
	 */
	private long _limit = Long.MAX_VALUE;
	/**
	 * Field isEmpty.
	 */
	private bool IsEmpty = true;
	
	/**
	 * Constructor for SqlBatch.
	 * @param header String
	 * @param tail String
	 */
	public SqlBatch(String header, String tail)
	{
		_header = header + "\n";
		_tail = (tail != null) && (tail.length() > 0) ? " " + tail + ";\n" : ";\n";
		_sb = new StringBuilder(_header);
		_result = new StringBuilder();
	}
	
	/**
	 * Constructor for SqlBatch.
	 * @param header String
	 */
	public SqlBatch(String header):this(header, null)
	{
	}
	
	/**
	 * Method writeStructure.
	 * @param str String
	 */
	public void writeStructure(String str)
	{
		_result.Append(str);
	}
	
	/**
	 * Method write.
	 * @param str String
	 */
	public void write(String str)
	{
		IsEmpty = false;
		if ((_sb.Length + str.length()) < (_limit - _tail.length()))
		{
			_sb.Append(str + ",\n");
		}
		else
		{
			_sb.Append(str + _tail);
			_result.Append(_sb.toString());
			_sb = new StringBuilder(_header);
		}
	}
	
	/**
	 * Method writeBuffer.
	 */
	public void writeBuffer()
	{
		var last = _sb.toString();
		if (last.length() > 0)
		{
			_result.Append(last.substring(0, last.length() - 2) + _tail);
		}
		_sb = new StringBuilder(_header);
	}
	
	/**
	 * Method close.
	 * @return String
	 */
	public String close()
	{
		if (_sb.Length > _header.length())
		{
			writeBuffer();
		}
		return _result.toString();
	}
	
	/**
	 * Method setLimit.
	 * @param l long
	 */
	public void setLimit(long l)
	{
		_limit = l;
	}
	
	/**
	 * Method isEmpty.
	 * @return boolean
	 */
	public bool isEmpty()
	{
		return IsEmpty;
	}
}

}
